package cn.tyoui.javacompiler;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;

import cn.tyoui.file.FileTools;
import cn.tyoui.tools.Tools;

/**
 * 动态编译类
 * 
 * @author 张伟
 * @version 1.0
 *
 */
public class JavaCompilerTools implements Tools{
	private static JavaCompilerTools tools = null;

	public static JavaCompilerTools initTool() {
		if (tools == null)
			return tools = new JavaCompilerTools();
		return tools;
	}

	private JavaCompilerTools() {
	}

	/**
	 * 动态编译
	 * 
	 * @param in
	 *            获得文件输入流
	 * @param out
	 *            结果输出流
	 * @param err
	 *            错误输出
	 * @param file
	 *            编译文件
	 * @return 是否编译成功
	 */
	public boolean compiler(String in, String out, String err, String... file) {
		FileTools tools = FileTools.initTool();
		JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
		return compiler.run(tools.getInputStream(in), tools.getOutputStream(out), tools.getOutputStream(err), file) == 0
				? true : false;
	}

	/**
	 * 无参数动态编译
	 * 
	 * @param file
	 *            文件地址
	 * @return 是否编译成功
	 */
	public boolean compiler(String... file) {
		return compiler(null, null, null, file);
	}

	/**
	 * 执行CMD窗口
	 * 
	 * @param order
	 *            cmd命令
	 * @return cmd打印输出信息
	 */
	public String getCMDContent(String order) {
		Runtime runtime = Runtime.getRuntime();
		String string = null;
		try {
			Process process = runtime.exec(order);
			InputStream stream = process.getInputStream();
			FileTools fileTools = FileTools.initTool();
			BufferedReader reader = fileTools.inputStreamGetBufferReader(stream);
			string = fileTools.readFileAll(reader);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return string;
	}
}
